package fleet_management

class UserController {

	def loginform(){
		render(view:'loginpage')
	}
	def loginpage(){
	}
	def login={
		def user=Admin.findByUserName(params.username)
		if(!user || params.password!=user.passWord){
			flash.message ="login failed"
			render(view:'loginpage')
			return
		}
		session.user=user.userName
		session.setAttribute("adminRole", user.region)
		def adminRole= session.getAttribute("adminRole")
		def offset=172800000
		def blueBookRenew=null
		if(adminRole=="Master Admin")
			blueBookRenew=VehicleDatabase.getAll()
		else
			blueBookRenew=VehicleDatabase.findByAdminRole(adminRole)

		if(blueBookRenew){
			def alertRenewMessage=""
			for(def d:blueBookRenew){
				Date dd=d.getBlueBookValidity()
				def conditionDate= new Date(dd.time-offset)
				if(conditionDate<=new Date()){
					alertRenewMessage+= "Renew Blue Book of VehicleNo "+d.getVehicleNumber()+"<br/>"
				}
			}
			flash.renewMessage=alertRenewMessage
		}
		def insuranceRenew=null
		if(adminRole=="Master Admin")
			insuranceRenew=VehicleDatabase.getAll()
		else
			insuranceRenew=VehicleDatabase.findByAdminRole(adminRole)
		if(insuranceRenew){
			def alertRenewMessage=""
			for(def d:insuranceRenew){
				Date dd=d.getInsuranceValidity()
				def conditionDate=new Date(dd.time-offset)
				if(conditionDate<=new Date()){
					alertRenewMessage+="Renew Insurance of VehicleNo "+d.getVehicleNumber()+"<br/>"
				}
			}
			flash.renewMessage2=alertRenewMessage
		}
		def servicingRenew=null
		if(adminRole=="Master Admin")
			servicingRenew=VehicleServicing.getAll()
		else
			servicingRenew=VehicleServicing.findByAdminRole(adminRole)
		if(servicingRenew){
			def alertRenewMessage=""
			for(def d:servicingRenew){
				Date dd=d.getServicingDueDate()
				def conditionDate=new Date(dd.time-offset)
				if(conditionDate<=new Date()){
					alertRenewMessage+="Send VehicleNo "+d.getVehicleNumber()+" to servicing."+"<br/>"
				}
			}
			flash.renewMessage3=alertRenewMessage
		}


		//		Date currentDate=new Date()
		//		def offset=172800000
		//		Date testDate=new Date(currentDate.time-offset)
		//		def renewDate=VehicleDescription.findByValidityOfBlueBook(testDate);
		//		if(renewDate){
		//			for(def d:renewDate){
		//			println "+++++++++++renew the bluebook "+d.getVehicleNumber()
		//			}
		//			}
		render(view:'homepage')
	}
	def logout={
		session.user=null
		flash.message ="Sucessfully logout"
		render(view:'loginpage')
	}
}
